<template>
  <div class="app-container">
    <div class="category-container">
      <el-scrollbar>
        <div class="category-list">
          <el-button
            v-for="category in categories"
            :key="category.id"
            :type="selectedCategoryId === category.id ? 'primary' : 'default'"
            @click="handleCategoryClick(category.id)"
          >
            {{ category.name }}
          </el-button>
        </div>
      </el-scrollbar>
    </div>

    <!-- 产品列表 -->
    <div class="product-container" v-loading="loading">
      <el-row :gutter="20">
        <el-col v-for="product in products" :key="product.id" :xs="24" :sm="12" :md="8" :lg="8" :xl="8">
          <el-card class="product-card" :body-style="{ padding: '0px' }">
            <div class="product-image" @click="handlePreviewImages(product)">
              <el-carousel
                v-if="product.productImages?.length > 1"
                :interval="4000"
                trigger="hover"
                indicator-position="outside"
                height="200px"
                @click.stop
              >
                <el-carousel-item v-for="image in product.productImages" :key="image.id">
                  <el-image :src="image.imageUrl" fit="cover" />
                </el-carousel-item>
              </el-carousel>

              <el-image
                v-else
                :src="getProductMainImage(product)"
                fit="cover"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>

              <div class="image-count" v-if="product.productImages?.length > 1">
                <el-icon><Picture /></el-icon>
                {{ product.productImages.length }}
              </div>
            </div>
            <div class="product-info">
              <div class="product-header">
                <h3 class="product-name">{{ product.name }}</h3>
                <div class="product-price">¥ {{ product.price }}</div>
              </div>
              <div class="product-tags">
                <el-tag v-if="product.isHot === 1" type="danger" size="small">热门</el-tag>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 无数据提示 -->
      <el-empty v-if="products.length === 0" description="暂无产品" />
    </div>

    <!-- 图片预览组件 -->
    <el-image-viewer
      v-if="showViewer"
      :url-list="previewUrls"
      :initial-index="previewIndex"
      @close="showViewer = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import request from '@/utils/request';

// 定义Product类型
interface Product {
  id: number;
  name: string;
  categoryId: number;
  price: string;
  description: string;
  status: number;
  isHot: number;
  productImages: {
    id: number;
    productId: number;
    imageUrl: string;
    sort: number;
  }[];
}

// 数据定义
const categories = ref([]);
const products = ref<Product[]>([]);
const selectedCategoryId = ref(null);
const loading = ref(false);

// 图片预览相关
const showViewer = ref(false);
const previewUrls = ref<string[]>([]);
const previewIndex = ref(0);

// 获取分类列表
const getCategories = async () => {
  try {
    const res = await request({
      url: '/productIndex/categories',
      method: 'get'
    });
    if (res.code === 200) {
      categories.value = res.data;
      // 如果有分类数据，默认选中第一个分类
      if (categories.value.length > 0) {
        handleCategoryClick(categories.value[0].id);
      }
    }
  } catch (error) {
    console.error('获取分类列表失败:', error);
    ElMessage.error('获取分类列表失败');
  }
};

// 获取分类下的产品
const getCategoryProducts = async (categoryId: number) => {
  loading.value = true;
  try {
    const res = await request({
      url: `/productIndex/category/${categoryId}/products`,
      method: 'get'
    });
    if (res.code === 200) {
      products.value = res.data;
    }
  } catch (error) {
    console.error('获取产品列表失败:', error);
    ElMessage.error('获取产品列表失败');
  } finally {
    loading.value = false;
  }
};

// 处理分类点击
const handleCategoryClick = (categoryId: number) => {
  selectedCategoryId.value = categoryId;
  getCategoryProducts(categoryId);
};

// 获取产品主图
const getProductMainImage = (product: Product) => {
  if (product.productImages && product.productImages.length > 0) {
    return product.productImages[0].imageUrl;
  }
  return ''; // 返回默认图片或空字符串
};

// 处理图片预览
const handlePreviewImages = (product: Product) => {
  if (product.productImages && product.productImages.length > 0) {
    previewUrls.value = product.productImages.map(img => img.imageUrl);
    previewIndex.value = 0;
    showViewer.value = true;
  }
};

// 页面加载时获取分类列表
onMounted(() => {
  getCategories();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
}

.page-title {
  margin: 0 0 20px;
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.category-container {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  .category-list {
    display: flex;
    gap: 10px;
    padding: 10px;

    .el-button {
      flex-shrink: 0;
    }
  }
}

.product-container {
  min-height: 400px;
  padding: 0 40px;
}

.product-card {
  margin-bottom: 20px;
  transition: all 0.3s;
  height: 100%;
  display: flex;
  flex-direction: column;

  &:hover {
    transform: translateY(-5px);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .product-image {
    height: 300px;
    overflow: hidden;
    position: relative;
    cursor: pointer;
    flex: none;

    .el-image {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }

    .el-carousel {
      height: 100%;

      :deep(.el-carousel__container) {
        height: 100%;
      }

      :deep(.el-carousel__item) {
        .el-image {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      :deep(.el-carousel__indicators) {
        transform: translateY(16px);
      }

      :deep(.el-carousel__button) {
        width: 8px;
        height: 8px;
        border-radius: 50%;
      }
    }

    .image-count {
      position: absolute;
      right: 8px;
      bottom: 8px;
      background-color: rgba(0, 0, 0, 0.6);
      color: #fff;
      padding: 4px 8px;
      border-radius: 12px;
      font-size: 12px;
      display: flex;
      align-items: center;
      gap: 4px;
      z-index: 1;
    }

    &:hover {
      &::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.1);
        z-index: 1;
      }
    }
  }

  .product-info {
    padding: 14px;
    padding-bottom: 8px;
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 80px;

    .product-header {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      margin-bottom: 8px;
    }

    .product-name {
      margin: 0;
      font-size: 16px;
      font-weight: 500;
      color: #333;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      flex: 1;
      padding-right: 10px;
    }

    .product-price {
      color: #f56c6c;
      font-size: 18px;
      font-weight: bold;
      white-space: nowrap;
    }

    .product-tags {
      margin-top: 0;

      .el-tag {
        margin: 0;
        padding: 0 6px;
        height: 20px;
        line-height: 20px;
      }
    }
  }
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}
</style>
